import Reflux from 'reflux';
import Actions from "./Actions";
import update from 'react-addons-update';
import {Control} from "react-keeper";
import DB from '../../../../app/db';
import StorageUtils from "../../../../app/storage";
import Utils from "../../../../utils/index";
import {RwCode, getInfoByOpenId} from "../../toupiao/const/Const"
import {Toast, Modal} from "antd-mobile";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    rwCode: null,
    isLoading: true,
    userInfo: {},
    rw: {},
    proprietor: {},
    doors: [],
    candidate: [],
    ywhVoteRole: false,
    headerContent: null,
    params: {},
    voteResult: {
      voted: false,
      votedDoorId: null
    }
  },

  initRw(rwCode) {
    this.data.rwCode = rwCode;
    this.data.isLoading = true;
    this.data.userInfo = update(this.data.userInfo, {$set: StorageUtils.getUser()});
    this.data.rw = update(this.data.rw, {$set: Control.state});
    this.data.doors = StorageUtils.getStorageItem('doors');
    this.data.proprietor = StorageUtils.getStorageItem('proprietor');
    this.data.voteResult = {voted: false, votedDoorId: null};
    this.updateComponent();
    this.initParams();
    this.getCandidates();
    this.ywhVoteRole();
    this.initVoteResult();
  },

  initParams() {

    let t = this;
    let params = {};
    let listHeader = null;

    let rw = this.data.rw;
    switch (this.data.rwCode) {
      case RwCode.CAST01:
        params = {
          courtId: rw.courtId,
          building: rw.building,
          unit: rw.unit,
          rwCode: RwCode.CAST01
        };
        listHeader = <div>单元长选举</div>;
        break;
      case RwCode.CAST02:
        params = {
          courtId: rw.courtId,
          building: rw.building,
          rwCode: RwCode.CAST02
        };
        listHeader = <div>楼栋长选举</div>;
        break;
      case RwCode.CAST03:
        params = {
          courtId: rw.courtId,
          rwCode: RwCode.CAST03
        };
        listHeader = <div>委员选举</div>;
        break;
      case RwCode.CAST04:
        params = {
          courtId: rw.courtId,
          rwCode: RwCode.CAST04
        };
        listHeader = <div>主任选举</div>;
        break;
      default:
        break;
    }
    t.data.headerContent = update(t.data.headerContent, {$set: listHeader});
    t.data.params = update(t.data.params, {$set: params});
    t.updateComponent();
  },

  initDoorAuth() {
    let t = this;
    let doors = t.data.doors;
    doors.map(door=>{
      let doorId = door.id;
      let pid = t.data.proprietor.id;
      DB.DoorAuth.authInfo({doorId: doorId, pid: pid}).then(
        function (content) {
          t.data.doors = update(t.data.doors, {$apply: doors=>{
            return doors.map(d=>{
              if (d.id === doorId) {
                return update(d, {
                  authInfo: {$set: content}
                })
              } else {
                return d;
              }
            });
          }});
          t.updateComponent();
        },
        function (error) {
          console.log(error);
        }
      );
    })
  },

  // 获取登陆用户是否有投票权
  ywhVoteRole() {

    let t = this;
    DB.ywh.ywhVoteRole({
      proprietorId: StorageUtils.getStorageItem('proprietor').id,
      ...t.data.params
    }).then(
      function (content) {
        t.data.ywhVoteRole = content;
        t.updateComponent();
      },
      function (error) {
        t.data.ywhVoteRole = false;
        t.updateComponent();
      }
    );
  },

  initVoteResult() {
    let t = this;
    DB.ywh.isVoted({
      proprietorId: t.data.proprietor.id,
      courtId: t.data.rw.courtId,
      building: t.data.rw.building,
      unit: t.data.rw.unit,
      rwCode: t.data.rwCode
    }).then(
      function (content) {
        t.data.voteResult = content;
        t.updateComponent();
      },
      function (error) {
        t.data.voteResult = {
          voted: false,
          votedDoorId: null
        };
        t.updateComponent();
      }
    );
  },

  // 业主名下所有门牌全部投
  ywhVote(data) {
    let t = this;

    Modal.alert('提示', '确定投他？', [
      {
        text: '投他',
        onPress: () => {
          DB.ywh.ywhVote({
            votedDoorId: data.id,
            proprietorId: t.data.proprietor.id,
            rwCode: t.data.rw.rwCode
          }).then(
            function (content) {
              Toast.success('投票成功');
              t.initVoteResult();
              t.getCandidates();
              t.getDoorsInfoByOpenId(t.data.userInfo.openId);
            },
            function (error) {
              Toast.fail('投票失败');
            }
          );
        },
        style: 'default'
      },
      {
        text: '取消',
        onPress: () => {},
        style: 'default'
      }
    ]);
  },

  getCandidates() {
    let t = this;
    let candidates = [];

    console.log(t.data.params);
    DB.ywh.getCandidates(t.data.params).then(
      function (content) {
        if (content) {
          console.log(content);
          content.map(c => {
            let voteCount = 0;
            switch (t.data.rwCode) {
              case RwCode.CAST01:
                voteCount = c.countUnit;
                break;
              case RwCode.CAST02:
                voteCount = c.countBuilding;
                break;
              case RwCode.CAST03:
                voteCount = c.countMember;
                break;
              case RwCode.CAST04:
                voteCount = c.countHead;
                break;
              default:
                break;
            }
            if (c)
              candidates.push({
                id: c.id,
                name: c.proprietorName,
                courtId: c.courtId,
                building: c.building,
                unit: c.unit,
                doorplateNo: c.doorplateNo,
                label: c.proprietorName+"（"+c.building+"栋"+c.unit+"单元"+c.doorplateNo+"）",
                extra: '得票：'+voteCount+'票'
              })
          })
        }
        console.log(candidates);
        t.data.candidate = update(t.data.candidate, {$set: candidates});
        t.data.isLoading = false;
        t.updateComponent();
      },
      function (error) {
        t.data.candidate = update(t.data.candidate, {$set: []});
        t.data.isLoading = false;
        t.updateComponent();
        console.log(error);
      }
    );
  },

  getDoorsInfoByOpenId(openId) {
    let t = this;
    DB.WechatAPI.getInfoByOpenId({
      openId: openId,
    }).then(
      function (content) {
        if (content.length > 0) {
          StorageUtils.setStorage('doors', content);
        } else {
          StorageUtils.removeStorageItem('doors');
        }
        t.data.doors = update(t.data.doors, {$set: content});
        t.updateComponent();
      },
      function (error) {
        StorageUtils.removeStorageItem('doors');
        t.data.doors = [];
        t.updateComponent();
        console.log(error);
      }
    ).catch(function (reason) {
      console.log(reason);
    });
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState() {
    return this.data;
  }
});
